﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;

namespace WpfApp3_Grid
{
    /// <summary>
    /// DisplayTreeWindow.xaml 的交互逻辑
    /// </summary>
    public partial class DisplayTreeWindow : Window
    {
        TreeView tree = new TreeView();
        TextBlock tb1 = new TextBlock()
        {
            Width = 400,
            Height = 200,
        };
        TextBlock tb2 = new TextBlock()
        {
            Width = 400,
            Height = 200,
        };
        DependencyObject closestAncestor;

        public DisplayTreeWindow()
        {
            //InitializeComponent();

            ScrollViewer sv = new ScrollViewer();
            this.Content = sv;

            StackPanel sp = new StackPanel();
            sp.Children.Add(tree);
            sp.Children.Add(tb1);
            sp.Children.Add(tb2);

            sv.Content = sp;
        }

        public void CreateLogicalTree(DependencyObject originalElement)
        {
            tree.Items.Clear();
            StringBuilder sb = new StringBuilder();
            closestAncestor = FindClosestLogicalAncestor(originalElement);
            sb.Append(closestAncestor.GetType().Name);
            tb1.Text = sb.ToString();

            sb.Remove(0, tb1.Text.Length);
            sb.Append("你选择了：").Append(originalElement.GetType().Name);
            tb2.Text = sb.ToString();

            DependencyObject rootElement = FindLogicalTreeRoot(closestAncestor);
            PopulateLogicalTree(null, rootElement);
            this.Title = "显示逻辑树";
        }

        public void CreateVisualTree(DependencyObject originalElement)
        {
            DependencyObject closestVisualAncestor = FindClosestVisualAncestor(originalElement);
            DependencyObject visualRoot = FindVisualTreeRoot(originalElement);

            StringBuilder sb = new StringBuilder();
            string closestParent = closestVisualAncestor == originalElement ? "(self)" : closestVisualAncestor.GetType().Name;
            sb.Append("最近视觉树上父节点：");
            sb.AppendLine();
            sb.Append("最近视觉树上父节点上的模板：");

            DependencyObject templatedParent = GetTemplatedParent(closestVisualAncestor);
            string strTemplatedParent = templatedParent == null ? "(null)" : templatedParent.GetType().Name;
            sb.Append(strTemplatedParent);
            tb1.Text = sb.ToString();
            sb.Remove(0, tb1.Text.Length);
            sb.Append("你选择了：").Append(originalElement.GetType().Name);
            tb2.Text = sb.ToString();
            PopulateVisualTree(null, visualRoot);
            this.Title = "显示视觉树";
        }

        private void PopulateLogicalTree(TreeViewItem parentItem, object currentElement)
        {
            TreeViewItem item = new TreeViewItem();
            item.IsExpanded = true;
            if (parentItem == null)
            {
                item.Header = currentElement.GetType().Name;
                tree.Items.Add(item);
            }
            else
            {
                item.Header = currentElement.GetType().Name;
                parentItem.Items.Add(item);
            }

            DependencyObject curObject = currentElement as DependencyObject;
            if (curObject != null)
            {
                foreach (object chElement in LogicalTreeHelper.GetChildren(curObject))
                {
                    PopulateLogicalTree(item, chElement);
                }
            }
        }

        private void PopulateVisualTree(TreeViewItem parentItem, DependencyObject currentElement)
        {
            TreeViewItem item = new TreeViewItem();
            item.IsExpanded = true;
            if (parentItem == null)
            {
                item.Header = currentElement.GetType().Name;
                tree.Items.Add(item);
            }
            else
            {
                item.Header = currentElement.GetType().Name;
                parentItem.Items.Add(item);
            }

            int visualChildrenCount = VisualTreeHelper.GetChildrenCount(currentElement);
            for (int i=0; i<visualChildrenCount; i++)
            {
                DependencyObject visualChild = VisualTreeHelper.GetChild(currentElement, i);
                PopulateVisualTree(item, visualChild);
            }
        }

        DependencyObject FindClosestLogicalAncestor(DependencyObject initial)
        {
            DependencyObject current = initial;
            DependencyObject result = initial;
            while(current != null)
            {
                DependencyObject logicalParent = LogicalTreeHelper.GetParent(current);
                if (logicalParent != null)
                {
                    result = current;
                    break;
                }
                current = VisualTreeHelper.GetParent(current);
            }
            return result;
        }

        DependencyObject FindLogicalTreeRoot(DependencyObject initial)
        {
            DependencyObject current = initial;
            DependencyObject result = initial;
            while (current != null)
            {
                result = current;
                current = VisualTreeHelper.GetParent(current);
            }
            return result;
        }

        DependencyObject GetTemplatedParent(DependencyObject depObj)
        {
            FrameworkElement fe = depObj as FrameworkElement;
            FrameworkContentElement fce = depObj as FrameworkContentElement;
            DependencyObject result;
            if (fe != null)
                result = fe.TemplatedParent;
            else if (fce != null)
                result = fce.TemplatedParent;
            else
                result = null;
            return result;
        }

        DependencyObject FindClosestVisualAncestor(DependencyObject initial)
        {
            if (initial is Visual || initial is Visual3D)
            {
                return initial;
            }

            DependencyObject current = initial;
            DependencyObject result = initial;
            while (current != null)
            {
                result = current;
                if (current is Visual || current is Visual3D)
                {
                    result = current;
                    break;
                }
                else
                {
                    current = LogicalTreeHelper.GetParent(current);
                }
            }
            return result;
        }

        DependencyObject FindVisualTreeRoot(DependencyObject initial)
        {
            DependencyObject current = initial;
            DependencyObject result = initial;
            while (current != null)
            {
                result = current;
                if (current is Visual || current is Visual3D)
                {
                    current = VisualTreeHelper.GetParent(current);
                }
                else
                {
                    current = LogicalTreeHelper.GetParent(current);
                }
            }
            return result;
        }
    }
}
